/*
 * This file is part of the Try! Engine project.
 *
 * Copyright 2010-2011 Emanuele Bertoldi. All rights reserved.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * You should have received a copy of the modified BSD License along with this
 * program. If not, see <http://www.opensource.org/licenses/bsd-license.php>
 */

#include "assetbrowserplugin.h"
#include <view3d.h>
#include <QtGui/QMenuBar>
#include <QtGui/QDockWidget>
#include <QtPlugin>

using namespace Try;

AssetBrowserPlugin::AssetBrowserPlugin(QObject* parent)
    :   QObject(parent),
        m_assetBrowser(0)
{
}

AssetBrowserPlugin::~AssetBrowserPlugin()
{
    this->shutdown();
}

QString AssetBrowserPlugin::name() const
{
    return tr("Asset Browser");
}

bool AssetBrowserPlugin::initialize(QMainWindow* parent)
{
    if (parent)
    {
        this->shutdown();

        // Widgets.
        m_assetBrowser = new AssetBrowser(parent);

        QDockWidget* ab_dock_widget = new QDockWidget(parent);
        ab_dock_widget->setWidget(m_assetBrowser);
        ab_dock_widget->setWindowTitle(m_assetBrowser->windowTitle());
        parent->addDockWidget(Qt::RightDockWidgetArea, ab_dock_widget);

        // Event filters.
        View3d* view3d = qobject_cast<View3d*>(parent->centralWidget());
        view3d->installEventFilter(m_assetBrowser);

        // Menus.
        QMenuBar* menu_bar = parent->menuBar();
        QMenu* view_menu = menu_bar->findChild<QMenu*>("menuView");

        QAction* asset_browser_action = ab_dock_widget->toggleViewAction();
        asset_browser_action->setText(tr("&Asset Browser"));

        view_menu->insertAction(0, asset_browser_action);

        // Connections.
        QObject::connect(m_assetBrowser, SIGNAL(destroyed()), ab_dock_widget, SLOT(deleteLater()));
        QObject::connect(m_assetBrowser, SIGNAL(destroyed()), asset_browser_action, SLOT(deleteLater()));

        return true;
    }

    return false;
}

bool AssetBrowserPlugin::shutdown()
{
    if (m_assetBrowser)
        delete m_assetBrowser;

    m_assetBrowser = 0;

    return true;
}

Q_EXPORT_PLUGIN2(assetbrowser, AssetBrowserPlugin)
